﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Chat</title>
    <link rel="shortcut icon" href="/images/favicon.ico" type="image/vnd.microsoft.icon" />
    <link rel="icon" href="/images/favicon.ico" type="x-icon" />
    <link rel="stylesheet" type="text/css" href="Styles/reset.css" />
    <link rel="stylesheet/less" type="text/css" href="Styles/chat.less" />
    <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
	<script src="Scripts/jquery.timers-1.2.js" type="text/javascript"></script>
	<script src="Scripts/jquery.hoverIntent.minified.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ucma.presence-1.0.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ucma.groupchat-1.0.js" type="text/javascript"></script>
    <script src="Scripts/less-1.1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.functions.js" type="text/javascript"></script>
    <script src="Scripts/jquery.localisation.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    	var chatHeight = 477;
    	var chatWidth = 456;

    	//still issue on chrome
    	try {
    		//window.resizeBy(439 - $(window).width(), 401 - $(window).height());
    		window.resizeTo(chatWidth, chatHeight);
    	} catch (err) {
    	}

        var groupSubscription;
        var webUserName;
        var topic;
        var state;
        var showpage;
        var session;

        // enum holding the states
        var STATES = {
            GetWebUserName: { value: 10 },
            Chat: { value: 20 },
            Closed: { value: 30 }
        };

        function onGroupLoaded(groupSubscriptionResult) {

            groupSubscription = groupSubscriptionResult;

            showPresence('', groupSubscription.GroupId);

            //generate a unique session identifier to call the service with
            session = Math.random();
            $(document).attr("title", groupSubscription.GroupName); // only syntax that works in IE<9

            //get employee name
            output("employeeMessage", "Hello, what's your name?");
            output("statusMessage", "Type your name and press ENTER.");
            changeState(STATES.GetWebUserName);

            //focus on message input
            $("#message").focus();

            $("#message").keyup(function (e) {
                if (e.keyCode == 13 && !e.shiftKey) { // Enter
                    handleMessageSendRequest();
                }
            });

        }

        function showPresence(employeeSip, groupId) {

            var show = false;

            if (employeeSip != null && employeeSip != '') {                
                //write the sip to the presence widget at the top
                $(".sip").html(employeeSip);
                show = true;
            }

            else if (groupId != null && groupId != '') {                
                $(".group").html(groupId);
                show = true;
            }


            if (show == true) {
            	$.presence({
            		'serviceUrl': 'https://lyncservice.domain.com/service.svc/',
            		'refreshRate': 5000,
            		'languageBaseUrl': 'http://lyncpresence.domain.com/Lang/widget',
            		'statusImageBaseUrl': 'http://lyncpresence.domain.com/StatusPictures/',
            		'statusImageExtension': '.jpg',
            		'onPresenceItemUpdated':
                      function (settings, presenceSubscription, presenceitem) {

                      	presenceStyling(settings, presenceSubscription, presenceitem, true);

                      	//check if we can still chat with the user
                      	var canChat = $.trim($(this).find(".canChat").html());
                      	if (canChat != "true" && state != STATES.Closed) {
                      		output("infoMessage", employeeName + " is no longer available for chat. You can send an email or place a call instead.");
                      		changeState(STATES.Closed);
                      		presenceitem.find(".button").addClass("highlight");
                      	}
                      },
            		'onGroupPresenceItemUpdated': function (settings, groupSubscription, presenceitem) {
            			if ($.trim($(".sip").html()) == '') {
            				$("#persontemplate").hide();
            				$("#grouptemplate").show();
            				groupPresenceStyling(settings, groupSubscription, presenceitem, true);
            			} else {
            				$("#grouptemplate").hide();
            				$("#persontemplate").show();
            			}
            		}
            	});
            }
        }


        $(document).ready(function () {            
            // init localisation
            $.localise('Lang/widget', { loadBase: true, timeout: 0 });

            //still issue on chrome
            try {
                //window.resizeBy(439 - $(window).width(), 401 - $(window).height());
                window.resizeTo(chatWidth, chatHeight);
            } catch(err) {
            }

            //get querystring parameters and put them in some vars
            groupId = getParameterByName("groupId");

            GetGroupPresence(groupId);

            output("statusMessage", "Please wait...");
        });


        function GetGroupPresence(groupid) {

        	$.ajax({
        		type: 'GET',
        		url: 'https://lyncservice.domain.com/service.svc/GetGroupPresence?groupid=' + groupid,
        		dataType: 'jsonp',
        		success: function(groupSubscription) {
        			onGroupLoaded(groupSubscription);
        		},
        		error: function(xhr, ajaxOptions, thrownError) {
        			//alert(thrownError);
        			setTimeout(function() {
        				GetGroupPresence(groupid);
        			}, 1000);
        		}
        	});
        }

        function onChatStarted(sip, message) {

            // output the message to the chat window
            output("employeeMessage", message);

            // show the presence of the group member
            showPresence(sip);

            // sets the last message received info
            setLastMessageReceived();
        }

        function InitChat() {

            $.chat({
                'serviceUrl': 'https://lyncservice.domain.com/service.svc/',
                'groupId': groupSubscription.GroupId,
                'huntGroupNumber': groupSubscription.HuntGroupNumber,
                'timeToWaitInSeconds': groupSubscription.TimeToWaitInSeconds,
                'userName': webUserName,
                'session': session,
                'refreshRate': 1000,
                'showpage': showpage,
                'topic': topic,
                'onError':
                function (errorMessage, isFatal) {
                    if (isFatal) {
                        output("infoMessage", "Error: " + errorMessage);
                        changeState(STATES.Closed);
                    } else {
                        output("infoMessage", "Error: " + errorMessage);
                    }
                },
                'onMessageReceived':
                function (sip, name, message, messageType) {

                    if (messageType == 'InstantMessage') {
                        onChatStarted(sip, message);
                    } if (messageType == 'ComposingStateChanged') {
                        var composingState = message;
                        if (composingState == "Idle") {
                            var currentLastMessageReceived = $("#lastMessageReceived").data("currentLastMessageReceived");
                            if (currentLastMessageReceived != undefined) {
                                $("#lastMessageReceived").html(currentLastMessageReceived);
                            } else {
                                $("#lastMessageReceived").html("");
                            }
                            $("#lastMessageReceived").removeClass("isTyping");
                        } else if (composingState == "Composing") {
                            output("statusMessage", name + " is typing a message...");
                            $("#lastMessageReceived").addClass("isTyping");
                        }
                    } else if (messageType == 'ServiceNotification') {
                        output("statusMessage", message);
                    } else if (messageType == 'ChatRequestAccepted') {
                        output("statusMessage", "Chat established.");
                    } else if (messageType == 'ChatRequestDenied') {
                        output("infoMessage", message);
                        changeState(STATES.Closed);
                    } else if (messageType == 'ServiceError') {
                        output("infoMessage", message);
                        changeState(STATES.Closed);
                    } else if (messageType == 'ChatClosed') {
                        output("infoMessage", message);
                        changeState(STATES.Closed);
                    }
                }
            });
        }

        function handleMessageSendRequest() {
            var message = readInput();
            if (message != '') {

                if (state == STATES.GetWebUserName) {
                    webUserName = message;
                    output("webUserMessage", message);
                    $(document).oneTime(1000, function () { // 1 second delay to catch the user's attention
                        output("employeeMessage", "Hi " + webUserName + ", your request has been sent, please wait for a response. We will help you right away.");
                    });
                    changeState(STATES.Chat);
                    InitChat();

                } else if (state == STATES.Chat) {
                    output("webUserMessage", message);
                    sendToServer(message, webUserName);
                }
            }
            clearInput();
            $("#message").focus();
        }

        function sendToServer(message, prefix) {
            if (!(prefix === undefined)) {
                message = prefix + ": " + message;
            }
            $.chat('sendToServer', message);
        }

        function changeState(newState) {
            if (newState == STATES.Chat) {
                output("statusMessage", "Opening chat...");
            } else if (newState == STATES.Closed) {
                $("#message").attr("disabled", "disabled");
                output("statusMessage", "");
                $.chat('dispose');
            }

            state = newState;
        }

        function clearInput() {
            $("#message").val("");
        }

        function readInput() {
            var input = $.trim($("#message").val());
            return input;
        }

        // writes a message to the conversation window. Chooses layout/template by type.
        function output(type, message) {

            //convert links to a href's
            message = message.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g, '<a href="$1" target="_blank">$1</a>');

            var previousOutput = $("#conversation > :last-child");

            if (type == "employeeMessage") {
                if (previousOutput.is(".fromEmployee")) {
                    //append to previous output container
                    previousOutput.append("<div class='content'>" + message + "</div>");
                } else {
                    //create new messageContainer
                    var templateData = [{ sender: groupSubscription.GroupName, message: message, time: getTimeString()}];
                    $("#employeeMessageTemplate").tmpl(templateData).appendTo("#conversation");
                }

            } else if (type == "webUserMessage") {
                if (previousOutput.is(".fromWebUser")) {
                    //append to previous output container
                    previousOutput.append("<div class='content'>" + message + "</div>");
                } else {
                    //create new messageContainer
                    var templateData = [{ sender: webUserName, message: message, time: getTimeString()}];
                    $("#webUserMessageTemplate").tmpl(templateData).appendTo("#conversation");
                }

            } else if (type == "infoMessage") {
                var templateData = [{ message: message}];
                $("#infoMessageTemplate").tmpl(templateData).appendTo("#conversation");

            } else if (type == "statusMessage") {
                $("#lastMessageReceived").html(message);
            }

            $("#conversation").scrollTop(99999);
        }

        function setLastMessageReceived() {
            $("#lastMessageReceived").html("Last message received on " + getDateString() + " at " + getTimeString() + ".");

            //store this string so that we can show it again when the lync user stops typing.
            $("#lastMessageReceived").data("currentLastMessageReceived", $("#lastMessageReceived").html());
        }

        function getTimeString() {
            var currentDate = new Date();
            var hours = currentDate.getHours();
            var minutes = currentDate.getMinutes();
            if (minutes < 10) minutes = "0" + minutes;
            return currentDate.getHours() + ":" + currentDate.getMinutes();
        }

        function getDateString() {
            var currentDate = new Date();
            var day = currentDate.getDate();
            var month = currentDate.getMonth();
            var year = currentDate.getFullYear();
            return day + "/" + month + "/" + year;
        }

        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        }

        $(window).bind("beforeunload", function () {
        	sendToServer("The web user closed the chat window.");
        });
    </script>
</head>
<body>
    <div id="chatWindow">
        <div id="chatWindowHeader">
            <div id="persontemplate">
                <div class="presenceitem">
                    <div class="availability">
                    </div>
                    <img class="statusImage" style="display: none;" />
                    <div class="sidePanel">
                        <div class="name">
                        </div>
                        <div class="status">
                        </div>
                        <div class="jobtitle">
                        </div>
                    </div>
                    <div class="buttons">
                        <div class="button emailbutton enabled">
                            <img class="emailIcon" src="images/email.png" />E-mail</div>
                        <div class="button phonebutton enabled">
                            <img class="phoneIcon" src="images/phone.png" />Phone</div>
                        <div class="phonetooltip hidden">
                            <div class="phoneContainer">
                                <img src="images/phone.png" />
                                <div>
                                    <div class="phonedescription">
                                        Work</div>
                                    <div class="phone">
                                    </div>
                                </div>
                            </div>
                            <div class="phoneContainer">
                                <img src="images/mobile.png" />
                                <div>
                                    <div class="phonedescription">
                                        Mobile</div>
                                    <div class="mobile">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sip hidden">
                    </div>
                    <div class="canChat hidden">
                    </div>
                    <div class="email hidden">
                    </div>
                </div>
            </div>
            <div id="grouptemplate">
                <div class="presenceitem">
                    <div class="availability">
                    </div>
                    <img class="statusImage" style="display: none;" />
                    <div class="sidePanel">
                        <div class="name">
                        </div>
                        <div class="status">
                        </div>
                        <div class="jobtitle">
                        </div>
                    </div>
                    <div class="buttons">
                        <div class="button emailbutton left enabled">
                            <img class="emailIcon" src="images/email.png" />E-mail</div>
                        <div class="button phonebutton right enabled">
                            <img class="phoneIcon" src="images/phone.png" />Phone</div>
                        <div class="phonetooltip right hidden">
                            <div class="phoneContainer">
                                <img src="images/phone.png" />
                                <div>
                                    <div class="phonedescription">
                                        Work</div>
                                    <div class="phone">
                                    </div>
                                </div>
                            </div>
                            <div class="phoneContainer">
                                <img src="images/mobile.png" />
                                <div>
                                    <div class="phonedescription">
                                        Mobile</div>
                                    <div class="mobile">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="group hidden">
                    </div>
                    <div class="canChat hidden">
                    </div>
                    <div class="email hidden">
                    </div>
                </div>
            </div>
        </div>
        <div id="chatWindowBody">
            <div id="conversation">
            </div>
            <div id="lastMessageReceived">
            </div>
            <div id="typeMessageContainer">
                <textarea id="message" style="resize: none;"></textarea><input type="button" id="btnSendMessage" value="Send" />
            </div>
        </div>
    </div>
    <!-- webUserMessageTemplate -->
    <script id="webUserMessageTemplate" type="text/html">
        <div class="messageContainer fromWebUser">
            <div class="sender">
                {{= sender}}</div>
            <div class="time">
                {{= time}}</div>
            <div class="content">{{html message}}</div>
        </div>
    </script>
    <!-- employeeMessageTemplate -->
    <script id="employeeMessageTemplate" type="text/html">
        <div class="messageContainer fromEmployee">
            <div class="sender">
                {{= sender}}</div>
            <div class="time">
                {{= time}}</div>
            <div class="content">{{html message}}</div>
        </div>
    </script>
    <!-- infoMessageTemplate -->
    <script id="infoMessageTemplate" type="text/html">
        <div class="infoContainer">
            <div class="content">
                {{= message}}
            </div>
        </div>
    </script>
</body>
</html>
